<template>
	<div class="flex-row">
		<div style="flex: 1 1 0%; height: 340px; overflow: auto;" class="f-left">
			<div>工单概况</div>
			<div class="container">
				<ul class="list">
					<li class="total-count">
						<span class="label">工单总数</span><br />
						<span class="count">{{ total_count }}</span>
					</li>
					<!-- 使用 v-for 循环渲染 data.gd 中的每一项 -->
					<li v-for="(item, index) in data.gd" :key="index" class="item">
						<span class="state">{{ item.state }}</span><br />
						<span class="count">{{ item.count }}</span>
					</li>
				</ul>
			</div>
		</div>

		<div class="f-right">
			<div>占比分析</div>
			<v-chart ref="mychart1" class="chart"></v-chart>
		</div>
	</div>
	<div class="below">
		<div class="b-left">
			 <div id="main" ref="chartRef" style="width: 100%; height: 400px;"></div>
		</div>
	</div>
</template>

<script setup>
import { onMounted, reactive, ref, onBeforeUnmount, computed, watch } from "vue";
import * as echarts from 'echarts';
import $http from "../router/AxiosApi";

// 数据响应式对象
const data = reactive({
  gd: [],
  count:[]
});

// 计算总数
const total_count = computed(() => {
  return data.gd.length > 0 ? data.gd[0].total_count : 0;
});

// 加载数据
const loadHouseNum = () => {
  $http.post("findOrderNum").then((res) => {
    console.log(res.data);
    data.gd = res.data;
  }).catch((error) => {
    console.error('Error fetching data:', error);
  });
};

// 图表实例
const mychart1 = ref(null);

// 图表选项
const optionPie = reactive({
  tooltip: {
    trigger: "item",
    formatter: "{a} <br/>{b} : {c} 个,占比： ({d}%)"
  },
  legend: {
    orient: "vertical",
    position: 'right',
    right: '2%',
    top: '20%',
    data: []
  },
  series: [{
    name: "任务类型占比分析表",
    type: "pie",
    radius: "70%",
    center: ["45%", "55%"],
    data: [],
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: "rgba(0, 0, 0, 0.5)"
      }
    },
    label: {
      show: true,
      formatter: '{b}个数占比：{d}%'
    }
  }]
});

// 渲染图表选项
const renderPieOptions = () => {
  if (!mychart1.value || data.gd.length === 0) return;

  // 更新图表选项
  optionPie.legend.data = data.gd.map(item => item.state);
  optionPie.series[0].data = data.gd.map(item => ({
    name: item.state,
    value: item.count
  }));

  // 设置图表选项
  mychart1.value.setOption(optionPie);
};

// 监视数据变化
watch(() => data.gd, renderPieOptions, { deep: true });

// 组件挂载后加载数据
onMounted(() => {
  loadHouseNum()
  loadCount();
});

// 组件卸载前销毁图表实例
onBeforeUnmount(() => {
  if (mychart1.value) {
    mychart1.value.dispose();
  }
});
const chartRef = ref(null);
const rowData=[]
const loadCount=()=>{
	$http.post("countOrder").then((res)=>{
		data.count=res.data
		console.log(data.count)
		 updateChart(data.count);
		})
}
const updateChart = (rawData) => {
    console.log(rawData);

    // 获取所有独特的执行者（姓名）
    const executors = [...new Set(rawData.map(item => item.executor))];
    const xAxisData = executors;

    // 准备数据
    const completedData = xAxisData.map(executor => {
        const item = rawData.find(data => data.executor === executor);
        return item ? item.completedOrders : 0;
    });
    const totalData = xAxisData.map(executor => {
        const item = rawData.find(data => data.executor === executor);
        return item ? item.total_count : 0;
    });

    // 设置图表的配置选项
    const optionUpdate = {
        yAxis: {
            type: 'value'
        },
        xAxis: {
            type: 'category',
            data: xAxisData
        },
        legend: {
            data: ['已完成', '全部']
        },
        series: [
            {
                name: '已完成',
                type: 'bar',
                barWidth: '40%',
                data: completedData,
                itemStyle: {
                    color: '#7f9c8c' // 可选：设置颜色
                },
                label: {
                    show: true,
                    position: 'top', // 数据标签显示在柱子上方
                    formatter: '{c}' // 显示数据值
                }
            },
            {
                name: '全部',
                type: 'bar',
                barWidth: '40%',
                data: totalData,
                itemStyle: {
                    color: '#ff6f61' // 可选：设置颜色
                },
                label: {
                    show: true,
                    position: 'top', // 数据标签显示在柱子上方
                    formatter: '{c}' // 显示数据值
                }
            }
        ],
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        }
    };

    // 初始化 ECharts 实例并设置配置项
    const myChart = echarts.init(chartRef.value);
    myChart.setOption(optionUpdate);

    // 可选: 处理图表的自适应大小
    window.addEventListener('resize', () => {
        myChart.resize();
    });
};



</script>

<style scoped>
	.chart {
		width: 100%;
		height: 300px;
	}

	.flex-row {
		display: -webkit-box;
		display: -ms-flexbox;
		display: flex;
		-webkit-box-orient: horizontal;
		-webkit-box-direction: normal;
		-ms-flex-direction: row;
		flex-direction: row;
	}

	.f-left {
		background-color: white;
		border-radius: 10px;
		padding: 10px;
		width: 700px;
		text-align: left;
	}

	.f-right {
		background-color: white;
		margin-left: 20px;
		width: 700px;
		text-align: left;
		padding: 10px;
		border-radius: 10px;
	}

	li {
		float: left;
		width: 400px;
	}

	ul {
		overflow: hidden;
	}

	.container {
		width: 100%;
		max-width: 600px;
		margin: 0 auto;
		padding: 20px;
	}

	.list {
		list-style: none;
		padding: 0;
		text-align: center;
	}

	.total-count {
		background-color: #f4f4f9;
		border-radius: 8px;
		padding: 20px;
		margin-bottom: 20px;
		box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	}

	.label {
		font-size: 16px;
		color: #555;
	}

	.count {
		font-size: 32px;
		color: #007bff;
		font-weight: bold;
	}

	.item {
		background-color: #ffffff;
		border-radius: 8px;
		padding: 15px;
		margin-bottom: 10px;
		box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	}

	.state {
		font-size: 18px;
		color: #333;
	}

	.item .count {
		font-size: 24px;
		color: #28a745;
		font-weight: bold;
	}
	.below{
		background-color: white;
		margin-top: 10px;
		border-radius: 10px;
	}
</style>